<?php
class Contact extends Controller{
    public function  __construct() {
        parent::Controller();
        $this->load->model('contactmodel','contact');
    }

    public function index(){
        if($contact = $this->contact->find()){
            $data['contact'] = $contact;
            $this->load->view('contact/index',$data);
        }else{
            redirect(base_url().'/admin.php?c=contact&m=create');
        }
    }

    public function create(){
        if($this->contact->find()){
            redirect('contact/edit');
        }else{
            $this->load->helper('form');
            $this->load->view('contact/create');
        }
    }

    public function add(){
        if($this->contact->find()){
            redirect(base_url().'/admin.php?c=contact$m=edit');
        }else{
            $this->load->library('form_validation');
			
			$this->form_validation->set_rules('telephone', '联系电话', 'required');
			$this->form_validation->set_rules('email', '电子邮箱', 'required|valid_email');
			$this->form_validation->set_rules('address', '详细地址', 'required');
			$this->form_validation->set_message('required',"%s不能为空！");
			$this->form_validation->set_message('valid_email',"%s格式错误！");
			
            if($this->form_validation->run()==false){
                $this->load->view('contact/create');
            }else{
                $this->contact->add();
                $this->session->set_flashdata('notice','添加成功！');
                redirect(base_url().'/admin.php?c=contact&m=index');
            }
        }
    }

    public function edit(){
        $this->load->library('form_validation');
		
        if($contact = $this->contact->find()){
            $data['contact'] = $contact;
            $this->load->view('contact/edit',$data);
        }else{
            redirect(base_url().'/admin.php?c=contact$m=create');
        }
    }

    public function update(){
        if($contact = $this->contact->find()){
            $this->load->library('form_validation');
			
			$this->form_validation->set_rules('telephone', '联系电话', 'required');
			$this->form_validation->set_rules('email', '电子邮箱', 'required|valid_email');
			$this->form_validation->set_rules('address', '详细地址', 'required');
		
            if($this->form_validation->run()==false){
                $this->contact->update();
                $this->session->set_flashdata('notice','修改成功！');
                redirect(base_url().'/admin.php?c=contact$m=index');
            }
        }else{
            redirect(base_url().'/admin.php?c=contact$m=create');
        }
    }
}
